package com.chenqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenqi.dao.CommentMapper;
import com.chenqi.model.dto.CommentDTO;
import com.chenqi.model.entity.Comment;
import com.chenqi.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/13-16-14
 */
@Slf4j
@Service
@Transactional(rollbackFor = {Exception.class})
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    public List<Comment> findCommentsByPostId(Integer pid) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("post_id", pid);
        queryWrapper.orderByDesc("create_time");
        List list = commentMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public int addComment(CommentDTO commentDTO) {
        try{
            Comment comment = new Comment();
            comment.setContent(commentDTO.getContent());
            comment.setUserId(commentDTO.getUserId());
            comment.setPostId(commentDTO.getPostId());
            comment.setUsername(commentDTO.getUsername());
            comment.setCreateTime(new Date());
            comment.setModifyTime(new Date());
            int i = commentMapper.insert(comment);
            return i;
        }catch (Exception e){
            log.error("Exception:{}", e.getMessage());
            return 0;
        }

    }
}
